package com.suyx.job.controller;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.suyx.job.entity.AnimalInfo;
import com.suyx.job.entity.Page;
import com.suyx.job.entity.Result;
import com.suyx.job.service.IAnimalInfoService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: suyx
 * @Date: 2018/10/31 0031 10:10
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/animal")
public class AnimalController  {

    private IAnimalInfoService animalService;

    @Autowired
    public AnimalController(IAnimalInfoService animalService) {
        this.animalService = animalService;
    }
    /**
     * 查询召唤兽信息
     */
    @GetMapping(value="/findAnimalPage")
    public Page findAnimalPage(AnimalInfo animalInfo, Integer page, Integer limit)
    {
        return animalService.findAnimalPage(animalInfo,page-1,limit);
    }

    /**
     * 保存召唤兽信息
     */
    @PostMapping("/saveAnimal")
    public Result saveAnimal(AnimalInfo animalInfo){
        try {
        	animalService.saveAndFlush(animalInfo);
            return new Result(true,"保存成功!");
        }catch (Exception e){
            log.error("保存召唤兽信息数据报错："+ExceptionUtils.getStackTrace(e));
            return new Result(false,"保存失败："+e.getMessage());
        }
    }

    /**
     * 删除召唤兽信息
     */
    @PostMapping("deleteAnimal")
    public Result deleteAnimal(Integer animalId){
        try {
        	animalService.deleteById(animalId);
            return new Result(true,"删除成功!");
        }catch (Exception e){
            log.error("删除召唤兽信息数据报错：" + ExceptionUtils.getStackTrace(e));
            return new Result(false,"删除失败："+e.getMessage());
        }
    }

    @PostMapping(value = "/updateStatus")
    public Result updateStatus(Integer animalId, String status) {
        try {
        	AnimalInfo animalInfo = animalService.getOne(animalId);
            if (animalInfo == null) {
                return new Result(false, "该id值不存在！操作失败");
            }
            animalInfo.setStatus(status);
            animalService.saveAndFlush(animalInfo);
            return new Result(true, "操作成功！");
        } catch (Exception e) {
            log.error("出现异常！" + ExceptionUtils.getStackTrace(e));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//捕获异常后进行回滚
            return new Result(false, "出现异常！" + e.getMessage());
        }
    }


}
